package com.icode.unsafe;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-11 13:39
 *
 *
 */
public class ListTest {

    public static void main(String[] args) {

        //ArrayList是线程不安全的
        // java.util.ConcurrentModificationException 并发修改异常
        //List<String> list = new ArrayList<>();

        //Vector是线程安全的，因为在方法上加了synchronize锁   Vector是JDK1.0  ArrayList是JDK1.2
        //List<String> list = new Vector<>();

        // CopyOnWriteArrayList的类中有添加了可重入锁，
        // final transient ReentrantLock lock = new ReentrantLock()
        //其中的每个写入方法都会去加锁
         List<String> list = new CopyOnWriteArrayList<>();

        //使用集合的工具类 底层加了synchronized(mutex){...}同步代码块
        //List<String> list = Collections.synchronizedList(new ArrayList<>());

        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                String uuId = UUID.randomUUID().toString().substring(0,5);
                list.add(uuId);
                System.out.println(list);
            }).start();
        }
    }
}
